package com.example.service.impl;

import com.example.dao.UserDao;
import com.example.dao.impl.UserDaoImpl;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.UploadDataUtil;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource(name = "userDao")
    public UserDao userDao;
    public User login(String username,String password) throws Exception {
       return userDao.login(username,password);
    }

    public Integer updatePass(Integer uId,String password) {
        int res = userDao.updatePass(uId,password);
        if(res == 1) {
            return 200;
        } else {
            return 500;
        }
    }

    public List<Map<String,Object>> getUserNewsList(Integer uId) {
        return userDao.getUserNewsList(uId);
    }

    public List<Map<String,Object>> getUserTopicList(Integer uId) {
        return userDao.getUserTopicList(uId);
    }

    public List<Map<String,Object>> getUserCollectionList(Integer uId) {
        return userDao.getUserCollectionList(uId);
    }
    public Map<String,Object> getTopic(Integer tId) {
        return userDao.getTopic(tId);
    }

    public Map<String,Object> getOtherUser(Integer uId) {
        return userDao.getOtherUser(uId);
    }

    public String uploadAvatar(MultipartFile file,Integer uId,HttpServletRequest request) {
        String newFileName = "";
        String fileName = file.getOriginalFilename();
        //选择了文件
        if(fileName.length() > 0){
            //上传至http://localhost:8080/forum/target/forum/upload目录
            String realpath = request.getServletContext().getRealPath("/upload");
            //实现文件上传
            String fileType = fileName.substring(fileName.lastIndexOf('.'));
            //防止文件名重名
            newFileName = UploadDataUtil.getNowTime() + fileType;
            File targetFile = new File(realpath, newFileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            //上传
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //保存到数据库中
        int res = userDao.updateAvatar(uId,newFileName);
        return newFileName;

    }

    public Integer updateInfo(Integer uId,String nickname,String phone,String email) {
        int res = userDao.updateInfo(uId,nickname,phone,email);
        if(res == 1) {
            return 200;
        } else {
            return 500;
        }
    }
}
